package com.ebocy.hammer.core.socket.server;
import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

import com.ebocy.hammer.core.handler.HandlerManager;
import com.ebocy.hammer.core.log.EbocyLogManager;
import com.ebocy.hammer.core.message.AbstractC2SMessage;
import com.ebocy.hammer.core.message.C2SExitGameMessage;
import com.ebocy.hammer.core.socket.MessageFilter;

public class ServerIoHandler extends IoHandlerAdapter {
	private static Logger logger = EbocyLogManager.getSystemLogger();
	private IoAcceptor acceptor;

    public ServerIoHandler(IoAcceptor acceptor){
        this.acceptor = acceptor;
    }

	/**
	 * 有新连接时触发
	 */
	@Override
	public void sessionOpened(IoSession session) throws Exception {
		logger.info("受管理的连接数：" + acceptor.getManagedSessionCount());
	}


	@Override
	public void exceptionCaught(IoSession ioSession, Throwable cause) {
		cause.printStackTrace();
	}

	@Override
	public void sessionClosed(IoSession ioSession) throws Exception {
		HandlerManager.resolveMessage(new C2SExitGameMessage(), ioSession);
		logger.info("总共接受消息数量" + MessageFilter.receive_num + "总共发送消息数量:"
				+ MessageFilter.send_num + "受管理的连接数："
				+ acceptor.getManagedSessionCount());
	}

	@Override
	public void messageReceived(IoSession ioSession, Object msg) throws Exception {
//		System.out.println("handler messageReceived: " + System.currentTimeMillis());

		HandlerManager.resolveMessage((AbstractC2SMessage)msg,ioSession);
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
//		System.out.println("handler messageSent: " + System.currentTimeMillis());

		super.messageSent(session, message);
	}
}
